define(function (require, exports, module) {
    'use strict';
    var $ = require('jquery'),
        _ = require('underscore'),
        Backbone = require('backbone'),
        notify = require('js/utils/notify'),
        user_models = require('js/apps/console/models'),
        models = require('js/apps/op/models'),
        utils = require('js/utils/tools'),
        cookie = require('js/utils/cookie'),
        app = Backbone.history,
        moment = require('moment');
    require('datetimepicker');
    require('datetimepicker');
    require('multiselect');
    require('magnific');

    var NotifyInternalView = Backbone.View.extend({
        tagName: "div",
        events: {
            'click a.delete-item': 'toDelete'
        },

        initialize: function (options) {
            this.options = options;
            this.collection = new models.NotifyInternalCollection();
            // this.user_collection = new user_models.UserCollection();
            this.collection.bind('change remove reset', this.renderWithData, this);
        },
        render: function () {
            this.$el.html("");
            $(window).scrollTop(0);
            return this;
        },
        doRefresh: function () {
            var options = this.options;
            options._ = new Date().getTime();
            app.navigate(utils.composeQueryString('#op/notify_internal/', options), {
                trigger: true
            });
        },
        toSaveOrCreate: function (e) {
            if (!utils.simpleCheck('#content-form')) {
                return;
            }
            var postBody = {};
            var content = {};
            content.title = $('#notify_title').val();
            content.body = $('#notify_info').val();
            content.tag = "站内消息";
            postBody.content = JSON.stringify(content);
            postBody.status = 0;
            postBody.expire_ts = moment(new Date().getTime()).unix();
            var user_ids = $('#user_id').val();
            user_ids = user_ids.replace(/，/ig, ',');
            user_ids = user_ids.replace(/\s*/g, "");
            var reg = /^[0-9,]+.?[0-9,]*$/;
            if (!reg.test(user_ids)) {
                notify.warning("注意", "输入ID包含非法字符");
                return;
            }
            postBody.user_ids = user_ids.split(',');
            postBody.notify_type = 4;
            postBody.created_by = 1;
            var that = this;
            var url;
            var type;
            if (e) {
                url = '/admin/notification/' + e;
                type = 'PUT'
            } else {
                url = '/admin/notification/';
                type = 'POST'
            }
            $.ajax({
                url: url,
                type: type,
                headers: {
                    'X-AUTH-USER': cookie.getCookie('bigbang_user_id'),
                    'X-AUTH-TOKEN': cookie.getCookie('bigbang_user_token'),
                    'content-type': 'application/json'
                },
                data: JSON.stringify(postBody)
            }).done(function (resp) {
                notify.success('提示', '新增成功！');
                that.doRefresh();
            }).fail(function (resp) {
                notify.error('Error', resp.statusText);
            });
        },
        toDelete: function (e) {
            utils.deleteItem(e, this.collection);
        },

        renderWithData: function () {
            this.$el.html(this.template({
                items: this.collection.toJSON(),
                searched: utils.getSearched('op/notify_internal'),
                overview: this.collection.overview,
            }));
            var that = this;

            $('#addNewItem').magnificPopup({
                items: {
                    src: '#addNewItemPanel',
                    type: 'inline'
                },
                midClick: true,
                closeOnBgClick: false,
                callbacks: {
                    beforeOpen: function () {
                        $(".panel-title").text("创建消息");
                        $("#user_id").attr("value", "");
                        $("#user_id").removeAttr("disabled");
                        $("#notify_title").attr("value", "");
                        $("#notify_info").val("");
                        $('#cancelAddNewItem').off('click').click(function () {
                            $.magnificPopup.close();
                        });

                        $('#confirmAddNewItem').off('click').click(function () {
                            that.toSaveOrCreate()
                            $.magnificPopup.close();
                        });
                    }
                }
            });
            $('.modifyItem').magnificPopup({
                items: {
                    src: '#addNewItemPanel',
                    type: 'inline'
                },
                midClick: true,
                closeOnBgClick: false,
                callbacks: {
                    beforeOpen: function () {
                        var data_id = $(this.st.el).closest('tr').data('id'),
                            choosen = that.collection.get(data_id);
                        $(".panel-title").text("修改消息");
                        $("#user_id").attr("value", choosen.get('user_id'));
                        $("#user_id").attr("disabled", "disabled");
                        $("#notify_title").attr("value", choosen.get('content')['title']);
                        $("#notify_info").val(choosen.get('content')['body']);
                        $('#cancelAddNewItem').off('click').click(function () {
                            $.magnificPopup.close();
                        });

                        $('#confirmAddNewItem').off('click').click(function () {
                            if ($("#notify_title").val() == choosen.get('content')['title'] &&
                                $("#notify_info").val() == choosen.get('content')['body']) {
                                notify.warning("提示", "没有修改任何值");
                            } else {
                                that.toSaveOrCreate(data_id);
                            }
                            $.magnificPopup.close();
                        });
                    }
                }
            });

            utils.renderTable('main-list', {
                $orderby: that.options.$orderby || '-created_at',
                sortCallback: function (field) {
                    that.options.$orderby = field;
                    that.options.$page = 1;
                    var newUrl = utils.composeQueryString('#op/notify_internal', that.options);
                    app.navigate(newUrl, {
                        trigger: true
                    });
                }
            });

            utils.getPaginator(that.options, this.collection.total, '#op/notify_internal/');
            return this;
        },
        load: function () {
            this.collection.fetch({
                reset: true,
                data: this.options,
                error: function (c, r, o) {
                    notify.notifyResp(r);
                    $('#content').append('<h4 class="text-muted">无数据</h4>');
                },
            });
        }
    });
    exports.List = Backbone.View.extend({
        el: "#content_wrapper",
        template: "op/NotifyInternal.html",
        initialize: function (options) {
            this.options = options;
        },
        render: function () {
            this.options.notify_type = 4;
            this.options.created_by = 1;
            var view = new NotifyInternalView(this.options);
            view.template = this.template;
            this.$el.empty();
            this.$el.append(view.render().el);
            view.load();
            return this;
        }
    });
});
